/**
 * 
 */
package se.thoka.twt.client.utils;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author Thobias Karlsson, Thoka
 * @since 8 jan 2010
 */
public class DOMUtil {

	/**
	 * Gets the child element of the supplied parent that has the supplied class
	 * name.
	 * 
	 * @param parent
	 *            The parent element
	 * @param className
	 *            The class name
	 * @return The element, or <code>null</code> if not found
	 */
	public static Element getChildByClassName(Element parent, String className) {
		Element result = null;
		for (int i = 0; result == null && i < DOM.getChildCount(parent); i++) {
			Element elem = DOM.getChild(parent, i);
			if (className.equals(elem.getClassName())) {
				result = elem;
			} else {
				result = getChildByClassName(elem, className);
			}
		}

		return result;
	}

	public static Element getChildById(Widget parent, String id) {
		return getChildById(parent.getElement(), id);
	}

	/**
	 * Gets the child element of the supplied parent that has the supplied
	 * identifier.
	 * 
	 * @param parent
	 *            The parent element
	 * @param id
	 *            The id
	 * @return The element, or <code>null</code> if not found
	 */
	public static Element getChildById(Element parent, String id) {
		Element result = null;
		for (int i = 0; result == null && i < DOM.getChildCount(parent); i++) {
			Element elem = DOM.getChild(parent, i);
			if (id.equals(elem.getId())) {
				result = elem;
			} else {
				result = getChildById(elem, id);
			}
		}

		return result;
	}

	/**
	 * Creates a widget from an element.
	 * 
	 * @param elem
	 *            The element
	 * @return The created widget
	 */
	public static Widget toWidget(Element elem) {
		return new ElementWidget(elem);
	}

	/**
	 * A widget that wraps a DOM element.
	 */
	public static class ElementWidget extends Widget {
		/**
		 * Creates a new instance of {@link DOMUtil.ElementWidget}.
		 * 
		 * @param elem
		 *            The element to create a widget from, must not be
		 *            <code>null</code>
		 */
		public ElementWidget(Element elem) {
			if (elem == null) {
				throw new NullPointerException("Element must not be null");
			}

			setElement(elem);
		}
	}
}
